package wx_service

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"peilian-api/app/global/variable"
	"peilian-api/app/model"
	"peilian-api/utils/tools"
)

type WxService struct {
}

func (wx *WxService) GetToken() (string, error) {
	appid := variable.Config.Wx.Appid
	secret := variable.Config.Wx.Secret

	// 先获取token 是否存在
	// sc := variable.DB.Redis.Get(appid)
	// access_token, err := sc.Result()
	// if err == nil && len(access_token) > 0 {
	// 	return access_token, nil
	// }

	// 调用api 生成token
	tokenUrl := variable.Config.Wx.TokenUrl
	getUrl := fmt.Sprintf("%s?grant_type=client_credential&appid=%s&secret=%s", tokenUrl, appid, secret)
	resp, err := http.Get(getUrl)
	if err != nil {
		return "", fmt.Errorf("token生成失败")
	}
	if resp != nil {
		defer resp.Body.Close()
	}
	res := make(map[string]interface{})
	err = tools.ReadResponseBody(resp, &res)
	if err != nil {
		return "", fmt.Errorf("token解析失败")
	}
	accessToken := res["access_token"].(string)
	// expiresIn := res["expires_in"].(float64)
	// if len(accessToken) > 0 && expiresIn > 7000 && expiresIn < 7300 {
	// 	sc2 := variable.DB.Redis.Set(appid, accessToken, 7000*time.Second)
	// 	fmt.Println(sc2.Err())
	// }
	return accessToken, nil
}

// 通过code获取phone
func (wx *WxService) GetUserPhoneNumberByCode(code string) (string, error) {
	// 获取token
	accessToken, err := wx.GetToken()
	if err != nil {
		return "", err
	}
	params := map[string]string{"code": code}
	reqData, _ := json.Marshal(params)
	resp, err := http.Post(
		fmt.Sprintf("%s?access_token=%s", variable.Config.Wx.UserPhoneNumber, accessToken),
		"application/json",
		bytes.NewReader(reqData),
	)
	if err != nil {
		return "", err
	}
	if resp != nil {
		defer resp.Body.Close()
	}
	res := model.PhoneInfoResp{}
	err = tools.ReadResponseBody(resp, &res)
	if err != nil {
		return "", err
	}
	if res.Errcode != 0 {
		return "", fmt.Errorf(res.Errmsg)
	}
	return res.PhoneInfo.PurePhoneNumber, nil
}

func (wx *WxService) GetWeAppSchema(path, query string) (string, error) {
	accessToken, err := wx.GetToken()
	if err != nil {
		return "", err
	}
	var envVersion string
	switch variable.Env {
	case "test":
		envVersion = "trial"
	case "prod":
		envVersion = "release"
	case "", "local":
		envVersion = "develop"
	default:
		envVersion = "release"
	}
	if path == "" {
		path = "/pages/changeMajor/index"
	}
	//path, _ = url.QueryUnescape(path)
	query = url.QueryEscape(query)
	query = "web_link_query=" + base64.URLEncoding.EncodeToString([]byte(query))
	params := map[string]interface{}{
		"jump_wxa": map[string]string{
			"path":        path,
			"query":       query,
			"env_version": envVersion,
		},
		"is_expire":       true,
		"expire_type":     1,
		"expire_interval": 30,
	}
	reqData, _ := json.Marshal(params)
	fmt.Println(string(reqData))
	url := fmt.Sprintf("%s?access_token=%s", variable.Config.Wx.GenerateSchema, accessToken)
	resp, err := http.Post(url, "application/json", bytes.NewReader(reqData))
	if err != nil {
		return "", err
	}
	if resp != nil {
		defer resp.Body.Close()
	}
	res := model.GenerateSchemeResp{}
	err = tools.ReadResponseBody(resp, &res)
	if err != nil {
		return "", err
	}
	if res.ErrCode != 0 {
		return "", fmt.Errorf(res.ErrMsg)
	}
	return res.OpenLink, nil
}
